<template>
  <div class="admin-panel">
    <div class="admin-sidebar">
      <div class="sidebar-header">
        <h2>管理后台</h2>
      </div>
      <nav class="sidebar-nav">
        <router-link to="/admin" class="nav-item">
          <el-icon><house /></el-icon>
          概览
        </router-link>
        <router-link to="/admin/users" class="nav-item">
          <el-icon><user /></el-icon>
          用户管理
        </router-link>
        <router-link to="/admin/games" class="nav-item">
          <el-icon><present /></el-icon>
          游戏管理
        </router-link>
        <router-link to="/admin/forum" class="nav-item">
          <el-icon><chat-dot-round /></el-icon>
          论坛管理
        </router-link>
        <router-link to="/admin/analytics" class="nav-item active">
          <el-icon><data-analysis /></el-icon>
          数据分析
        </router-link>
        <router-link to="/" class="nav-item">
          <el-icon><back /></el-icon>
          返回首页
        </router-link>
      </nav>
    </div>
    
    <div class="admin-content">
      <div class="content-header">
        <h1>数据分析</h1>
        <div class="refresh-btn" @click="loadAnalyticsData">
          <el-icon><refresh /></el-icon>
          刷新数据
        </div>
      </div>
      
      <div class="analytics-container">
        <!-- 图表网格 -->
        <div class="charts-grid">
          <div class="chart-card">
            <h3>评分最高的游戏</h3>
            <div ref="topRatedChart" class="chart"></div>
          </div>
          
          <div class="chart-card">
            <h3>最受欢迎的游戏（点赞数）</h3>
            <div ref="mostLikedChart" class="chart"></div>
          </div>
          
          <div class="chart-card">
            <h3>评论最多的游戏</h3>
            <div ref="mostCommentedChart" class="chart"></div>
          </div>
          
          <div class="chart-card">
            <h3>收藏最多的游戏</h3>
            <div ref="mostFavoritedChart" class="chart"></div>
          </div>
          
          <div class="chart-card full-width">
            <h3>游戏分类分布</h3>
            <div ref="categoryChart" class="chart"></div>
          </div>
        </div>
      </div>
    </div>
  </div>
</template>

<script>
import { ref, onMounted, nextTick, onUnmounted } from 'vue'
import { ElMessage } from 'element-plus'
import * as echarts from 'echarts'
import { analyticsAPI } from '../api'

export default {
  name: 'Analytics',
  setup() {
    const topRatedChart = ref(null)
    const mostLikedChart = ref(null)
    const mostCommentedChart = ref(null)
    const mostFavoritedChart = ref(null)
    const categoryChart = ref(null)
    
    const analyticsData = ref({
      topRatedGames: [],
      mostLikedGames: [],
      mostCommentedGames: [],
      mostFavoritedGames: [],
      categoryStats: []
    })
    
    const loadAnalyticsData = async () => {
      try {
        const response = await analyticsAPI.getDashboardData()
        if (response.code === 200) {
          analyticsData.value = response.data
          await nextTick()
          initCharts()
        }
      } catch (error) {
        console.error('加载分析数据失败:', error)
        ElMessage.error('加载分析数据失败')
      }
    }
    
    const initCharts = () => {
      initTopRatedChart()
      initMostLikedChart()
      initMostCommentedChart()
      initMostFavoritedChart()
      initCategoryChart()
    }
    
    const initTopRatedChart = () => {
      const chart = echarts.init(topRatedChart.value)
      const option = {
        tooltip: {
          trigger: 'axis',
          axisPointer: {
            type: 'shadow'
          }
        },
        grid: {
          left: '3%',
          right: '4%',
          bottom: '3%',
          containLabel: true
        },
        xAxis: {
          type: 'value'
        },
        yAxis: {
          type: 'category',
          data: analyticsData.value.topRatedGames.map(item => item.title)
        },
        series: [{
          name: '评分',
          type: 'bar',
          data: analyticsData.value.topRatedGames.map(item => item.averageRating),
          itemStyle: {
            color: new echarts.graphic.LinearGradient(0, 0, 1, 0, [{
              offset: 0,
              color: '#667eea'
            }, {
              offset: 1,
              color: '#764ba2'
            }])
          }
        }]
      }
      chart.setOption(option)
    }
    
    const initMostLikedChart = () => {
      const chart = echarts.init(mostLikedChart.value)
      const option = {
        tooltip: {
          trigger: 'axis',
          axisPointer: {
            type: 'shadow'
          }
        },
        grid: {
          left: '3%',
          right: '4%',
          bottom: '3%',
          containLabel: true
        },
        xAxis: {
          type: 'value'
        },
        yAxis: {
          type: 'category',
          data: analyticsData.value.mostLikedGames.map(item => item.title)
        },
        series: [{
          name: '点赞数',
          type: 'bar',
          data: analyticsData.value.mostLikedGames.map(item => item.likeCount),
          itemStyle: {
            color: new echarts.graphic.LinearGradient(0, 0, 1, 0, [{
              offset: 0,
              color: '#f093fb'
            }, {
              offset: 1,
              color: '#f5576c'
            }])
          }
        }]
      }
      chart.setOption(option)
    }
    
    const initMostCommentedChart = () => {
      const chart = echarts.init(mostCommentedChart.value)
      const option = {
        tooltip: {
          trigger: 'axis',
          axisPointer: {
            type: 'shadow'
          }
        },
        grid: {
          left: '3%',
          right: '4%',
          bottom: '3%',
          containLabel: true
        },
        xAxis: {
          type: 'value'
        },
        yAxis: {
          type: 'category',
          data: analyticsData.value.mostCommentedGames.map(item => item.title)
        },
        series: [{
          name: '评论数',
          type: 'bar',
          data: analyticsData.value.mostCommentedGames.map(item => item.commentCount),
          itemStyle: {
            color: new echarts.graphic.LinearGradient(0, 0, 1, 0, [{
              offset: 0,
              color: '#4facfe'
            }, {
              offset: 1,
              color: '#00f2fe'
            }])
          }
        }]
      }
      chart.setOption(option)
    }
    
    const initMostFavoritedChart = () => {
      const chart = echarts.init(mostFavoritedChart.value)
      const option = {
        tooltip: {
          trigger: 'axis',
          axisPointer: {
            type: 'shadow'
          }
        },
        grid: {
          left: '3%',
          right: '4%',
          bottom: '3%',
          containLabel: true
        },
        xAxis: {
          type: 'value'
        },
        yAxis: {
          type: 'category',
          data: analyticsData.value.mostFavoritedGames.map(item => item.title)
        },
        series: [{
          name: '收藏数',
          type: 'bar',
          data: analyticsData.value.mostFavoritedGames.map(item => item.favoriteCount),
          itemStyle: {
            color: new echarts.graphic.LinearGradient(0, 0, 1, 0, [{
              offset: 0,
              color: '#ffecd2'
            }, {
              offset: 1,
              color: '#fcb69f'
            }])
          }
        }]
      }
      chart.setOption(option)
    }
    
    const initCategoryChart = () => {
      const chart = echarts.init(categoryChart.value)
      const option = {
        tooltip: {
          trigger: 'item',
          formatter: '{a} <br/>{b} : {c} ({d}%)'
        },
        legend: {
          type: 'scroll',
          orient: 'vertical',
          right: 10,
          top: 20,
          bottom: 20,
          data: analyticsData.value.categoryStats.map(item => item.category)
        },
        series: [{
          name: '游戏分类',
          type: 'pie',
          radius: '55%',
          center: ['40%', '50%'],
          data: analyticsData.value.categoryStats.map(item => ({
            value: item.count,
            name: item.category
          })),
          emphasis: {
            itemStyle: {
              shadowBlur: 10,
              shadowOffsetX: 0,
              shadowColor: 'rgba(0, 0, 0, 0.5)'
            }
          },
          itemStyle: {
            color: function(params) {
              const colors = ['#667eea', '#f093fb', '#4facfe', '#ffecd2', '#a8edea', '#fed6e3']
              return colors[params.dataIndex % colors.length]
            }
          }
        }]
      }
      chart.setOption(option)
    }

    let timer = null

    const startAutoRefresh = () => {
      // 先清掉旧定时器，防止重复启动
      stopAutoRefresh()

      // 每 30 秒自动拉一次数据
      timer = setInterval(() => {
        loadAnalyticsData()
      }, 30 * 1000)
    }

    const stopAutoRefresh = () => {
      if (timer) {
        clearInterval(timer)
        timer = null
      }
    }

    // 组件挂载时启动
    onMounted(() => {
      loadAnalyticsData()
      startAutoRefresh()
    })

// 组件卸载时清理
    onUnmounted(() => {
      stopAutoRefresh()
    })

    return {
      topRatedChart,
      mostLikedChart,
      mostCommentedChart,
      mostFavoritedChart,
      categoryChart,
      loadAnalyticsData,
      startAutoRefresh,
      stopAutoRefresh
    }
  }
}
</script>

<style scoped>
.admin-panel {
  display: flex;
  min-height: 100vh;
  background: #f5f5f5;
}

.admin-sidebar {
  width: 250px;
  background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
  color: white;
  padding: 0;
  position: fixed;
  height: 100vh;
  left: 0;
  top: 0;
  overflow-y: auto;
}

.sidebar-header {
  padding: 2rem 1.5rem;
  border-bottom: 1px solid rgba(255, 255, 255, 0.1);
}

.sidebar-header h2 {
  margin: 0;
  font-size: 1.5rem;
  font-weight: bold;
}

.sidebar-nav {
  padding: 1rem 0;
}

.nav-item {
  display: flex;
  align-items: center;
  gap: 0.8rem;
  color: white;
  text-decoration: none;
  padding: 1rem 1.5rem;
  transition: all 0.3s ease;
  border-left: 3px solid transparent;
}

.nav-item:hover {
  background: rgba(255, 255, 255, 0.1);
  border-left-color: white;
}

.nav-item.active {
  background: rgba(255, 255, 255, 0.2);
  border-left-color: white;
}

.admin-content {
  flex: 1;
  margin-left: 250px;
  padding: 2rem;
}

.content-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 2rem;
}

.content-header h1 {
  color: #333;
  font-size: 2rem;
  margin: 0;
}

.refresh-btn {
  background: linear-gradient(135deg, #4facfe 0%, #00f2fe 100%);
  color: white;
  padding: 0.8rem 1.5rem;
  border-radius: 8px;
  cursor: pointer;
  display: flex;
  align-items: center;
  gap: 0.5rem;
  transition: all 0.3s ease;
}

.refresh-btn:hover {
  transform: translateY(-2px);
  box-shadow: 0 4px 12px rgba(79, 172, 254, 0.4);
}

.analytics-container {
  background: white;
  border-radius: 12px;
  box-shadow: 0 4px 15px rgba(0, 0, 0, 0.1);
  padding: 2rem;
}

.charts-grid {
  display: grid;
  grid-template-columns: repeat(auto-fit, minmax(400px, 1fr));
  gap: 2rem;
}

.chart-card {
  background: #f8f9fa;
  border-radius: 8px;
  padding: 1.5rem;
  box-shadow: 0 2px 8px rgba(0, 0, 0, 0.1);
}

.chart-card.full-width {
  grid-column: 1 / -1;
}

.chart-card h3 {
  margin: 0 0 1rem 0;
  color: #333;
  font-size: 1.1rem;
}

.chart {
  height: 300px;
  width: 100%;
}

.chart-card.full-width .chart {
  height: 400px;
}

/* 响应式设计 */
@media (max-width: 768px) {
  .admin-sidebar {
    width: 200px;
  }
  
  .admin-content {
    margin-left: 200px;
    padding: 1rem;
  }
  
  .charts-grid {
    grid-template-columns: 1fr;
    gap: 1rem;
  }
  
  .chart-card {
    padding: 1rem;
  }
  
  .chart {
    height: 250px;
  }
}

@media (max-width: 480px) {
  .admin-sidebar {
    width: 100%;
    position: relative;
    height: auto;
  }
  
  .admin-content {
    margin-left: 0;
  }
  
  .content-header {
    flex-direction: column;
    gap: 1rem;
    align-items: flex-start;
  }
}
</style>